package cat.service.impl;

import cat.entity.Article;
import cat.entity.ArticleCategoryRef;
import cat.entity.ArticleTagRef;
import cat.entity.Category;
import cat.mapper.ArticleCategoryRefMapper;
import cat.mapper.ArticleMapper;
import cat.mapper.ArticleTagRefMapper;
import cat.service.ArticleService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
public class ArticleServiceImpl implements ArticleService {

    @Resource
    ArticleMapper articleMapper;

    @Resource
    ArticleCategoryRefMapper articleCategoryRefMapper;

    @Resource
    ArticleTagRefMapper articleTagRefMapper;

    public List<Article> listRecentArticle(Integer n) {
        return articleMapper.listRecentArticle(n);
    }

    /*
    根据id查询
     */
    public Article selectArticleById(int articleId) {
        return articleMapper.selectArticleById(articleId);
    }

    /*
    分页查询
     */
    public PageInfo<Article> getPageArticleList(Integer pageIndex, Integer pageSize) {
        PageHelper.startPage(pageIndex,pageSize);
        List<Article> articleList = articleMapper.findAll();
        //对每个文章，查出他对应的分类信息
        for (Article a : articleList) {
            List<Category> categoryList=articleCategoryRefMapper.listCategoryByArticleId(a.getArticleId());
            a.setCategoryList(categoryList);
        }
        return new PageInfo<Article>(articleList);
    }


    public void deleteArticleById(Integer articleId) {
        articleMapper.deleteArticleById(articleId);
    }

    /**
     * 添加文章
     */
    public void addArticle(Article article) {
        article.setArticleCreateTime(new Date());
        article.setArticleUpdateTime(new Date());

        //点击次数,点赞次数,评论次数默认都是0
        article.setArticleViewCount(0);
        article.setArticleLikeCount(0);
        article.setArticleCommentCount(0);
        article.setArticleOrder(1);

        //把文章表的信息添进去
        articleMapper.addArticle(article);

        //添加文章和分类的对应
        for(int i=0;i<article.getCategoryList().size();i++) {
            ArticleCategoryRef articleCate =new ArticleCategoryRef(article.getArticleId(),article.getCategoryList().get(i).getCategoryId());
            articleCategoryRefMapper.addArticleCategory(articleCate);
        }

        //添加文章和标签的对应
        for(int i=0;i<article.getTagList().size();i++) {
            ArticleTagRef articleTag =new ArticleTagRef(article.getArticleId(),article.getTagList().get(i).getTagId());
            articleTagRefMapper.addArticleTag(articleTag);
        }
    }
}


